package org.linlinjava.litemall.core.feie;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FeiEService {
    @Value("${litemall.feie.user}")
    private String USER;
    @Value("${litemall.feie.uKey}")
    private String UKEY;
    @Value("${litemall.feie.url}")
    private String URL;

    public String addPrinters(List<PrinterInfo> printers) {
        if (CollectionUtils.isEmpty(printers)) {
            return null;
        }
        String content = "";
        for (PrinterInfo printer : printers) {
            if (StringUtils.isNotEmpty(content)) {
                content += "\\n";
            }
            content += printer.getSn() + "#" + printer.getKey() + "#" + printer.getName();
        }

        String method = "Open_printerAddlist";
        Map<String, String> param = new HashMap<>();
        param.put("printerContent", content);
        String result = exec(method, param);
        return result;
    }

    public String deletePrinters(List<PrinterInfo> printers) {
        if (CollectionUtils.isEmpty(printers)) {
            return null;
        }
        String content = "";
        for (PrinterInfo printer : printers) {
            if (StringUtils.isNotEmpty(content)) {
                content += "-";
            }
            content += printer.getSn();
        }

        String method = "Open_printerDelList";
        Map<String, String> param = new HashMap<>();
        param.put("snlist", content);
        String result = exec(method, param);
        return result;
    }

    public String printMsg(String sn, String content) {
        return printMsg(sn, content, 1);
    }

    public String printMsg(String sn, String content, int times) {
        String method = "Open_printMsg";
        Map<String, String> param = new HashMap<>();
        param.put("sn", sn);
        param.put("content", content);
        param.put("times", times+"");
        String result = exec(method, param);
        return result;
    }

    private String exec(String method, Map<String, String> param) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
        nvps.add(new BasicNameValuePair("apiname",method));
        for (Map.Entry<String, String> stringObjectEntry : param.entrySet()) {
            nvps.add(new BasicNameValuePair(stringObjectEntry.getKey(), stringObjectEntry.getValue()));
        }

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //生成签名字符串
    private static String signature(String USER,String UKEY,String STIME){
        String s = DigestUtils.sha1Hex(USER+UKEY+STIME);
        return s;
    }
}
